package cn.demomaster.quickpermission

import android.Manifest
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import cn.demomaster.quickpermission.util.PermissionGroupUtil
import cn.demomaster.quickpermission.util.PreferenceManager

class PermissionRequester() : Requester, Requester2 {

    private var requestCode: Int = 0
    private var requestCompleted: Boolean = false
    private lateinit var currentPermission: String
    private var permissions = mutableListOf<String>()
    private var onRationale: ((String) -> Unit)? = null//拒绝多次无法继续申请，要去应用详情页面操作
    private var onGranted: (() -> Unit)? = null//允许
    private var onDenied: ((String) -> Unit)? = null//权限被拒绝
    private var onStart: ((Requester) -> Unit)? = null//第一次申请
    private var onStart2: ((Activity, String, Requester2) -> Unit)? = null//每个权限申请都会回调

    fun startRequest(activity: Activity) {
        if (permissions.isEmpty()) {
            throw IllegalArgumentException("No permissions to request")
        }
        //判断是否有待授权的权限
        var existPermission = false
        for (p in permissions) {
            if (!QuickPermission.checkPermission(activity, p)) {
                existPermission = true
                break
            }
        }
        if (!existPermission) {
            doPermissionsGranted(activity)
            return
        } else {
            if (this.onStart != null) {
                this.onStart!!.invoke(this)
            } else {
                innerRequest(activity)
            }
        }
    }

    private fun innerRequest(activity: Activity) {
//        val deniedPermissions = permissions.filter { permission ->
//            ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
//        }
        for (p in permissions) {
            if (!QuickPermission.checkPermission(activity, p)) {
                this.currentPermission = p
                this.requestCompleted = false
                requestPermissionImpl(activity, currentPermission, this.requestCode)
                return
            }
        }
        doPermissionsGranted(activity)
    }

    private fun doRationale(activity: Activity, p: String) {
        if (onRationale == null) {
            showRationaleDialog(activity,p)
        } else {
            onRationale!!.invoke(p)
        }
    }

    var rationaleDialog: AlertDialog? = null
    private fun showRationaleDialog(activity: Activity, p: String) {
        rationaleDialog = AlertDialog.Builder(activity)
            .setTitle("权限请求")
            .setMessage("您已禁止再次请求$p 权限，请手动开启。")
            .setPositiveButton(
                "好的"
            ) { dialog: DialogInterface?, which: Int ->
                openAppSettings(activity)
            }
            .show()
    }
    private fun openAppSettings(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", activity.packageName, null)
        intent.data = uri
        activity.startActivity(intent)
    }
    private fun doPermissionsGranted(activity: Activity) {
        this.requestCompleted = true
        onGranted?.invoke()
    }

    private fun onPermissionDenied(permission: String) {
        this.requestCompleted = true;
        if (onDenied == null) {
            //showDeniedDialog(permission)
        } else {
            onDenied!!.invoke(permission)
        }
    }

    private fun requestPermissionImpl(
        activity: Activity,
        permissionName: String,
        requestCode: Int,
        callBySelf: Boolean = true
    ) {
        println("权限申请:" + permissionName + ",RequestCode:" + requestCode + ",[" + permissionName + "]")
        if (callBySelf && onStart2 != null) {
            onStart2?.invoke(activity, permissionName, this)
            return
        }
        when (permissionName) {
            Manifest.permission.REQUEST_INSTALL_PACKAGES,
            Manifest.permission.INSTALL_PACKAGES,
            Manifest.permission.SYSTEM_ALERT_WINDOW,
            Manifest.permission.PACKAGE_USAGE_STATS,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.BIND_ACCESSIBILITY_SERVICE,
            Manifest.permission.MANAGE_EXTERNAL_STORAGE ->
                QuickPermission.startPermissionActivity(activity, permissionName, requestCode)

            else -> {
                ActivityCompat.requestPermissions(
                    activity,
                    permissions.toTypedArray(),
                    //listOf(permissionName).toTypedArray(),
                    requestCode
                )
            }
        }
        PreferenceManager.setPermissionRequested(activity, permissionName, true)
    }

    fun onRequestPermissionsResult(
        activity: Activity,
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
            doResult(activity)
    }

    fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
            doResult(activity)
    }

    private fun doResult(activity: Activity) {
        if (requestCode != this.requestCode) {
            return
        }
        for (p in permissions) {
            if (!QuickPermission.checkPermission(activity, p)) {
                if (p.equals(currentPermission)) {//检查第一个被拒绝的权限是否已经申请过了，如果已经申请过了则不用继续申请了，否则继续
                    if (!PermissionGroupUtil.isSpecialPermission(p)) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, p)) {
                            System.out.println("权限第" + PreferenceManager.getDeniedCount(activity, p) + "次被拒绝:" + p)
                            PreferenceManager.onPermissionDenied(activity, p)
                            PreferenceManager.setPermissionRequested(activity, p, true)
                        } else {
                            if (PreferenceManager.hasRequestedPermission(activity, p) && PreferenceManager.isBlackPermission(activity, p)) {
                                System.out.println("取消授权请求:" + p)
                                doRationale(activity,p)
                                return
                            } else {
                                System.out.println("第一次请求授权:" + p)
                            }
                        }
                    }
                    onPermissionDenied(p)
                    return
                } else {
                    System.out.println("还有未授权的，继续下一个权限：" + currentPermission)
                    requestPermissionImpl(activity, currentPermission, this.requestCode)
                    return
                }
            }

        }
        doPermissionsGranted(activity)
    }

    override fun continueRequest(activity: Activity) {
        innerRequest(activity)
    }

    override fun cancelRequest(activity: Activity) {
        this.onStart = null
        this.onStart2 = null
        this.onRationale = null
        this.onGranted = null
        this.onDenied = null
        QuickPermission.request = null
    }

    override fun continueRequest2(activity: Activity, permission: String) {
        requestPermissionImpl(activity, permission, this.requestCode, false)
    }

    override fun cancelRequest2(activity: Activity) {
        this.onStart = null
        this.onStart2 = null
        this.onRationale = null
        this.onGranted = null
        this.onDenied = null
        QuickPermission.request = null
        if (rationaleDialog!=null&&rationaleDialog!!.isShowing){
            rationaleDialog!!.dismiss()
            rationaleDialog = null
        }
    }

    class Builder(private val activity: Activity) {
        private val permissions = mutableListOf<String>()
        private var onRationale: ((String) -> Unit)? = null//拒绝多次无法继续申请，要去应用详情页面操作
        private var onGranted: (() -> Unit)? = null//允许
        private var onDenied: ((String) -> Unit)? = null//权限被拒绝
        private var onStart: ((Requester) -> Unit)? = null//第一次申请
        private var onStart2: ((Activity, String, Requester2) -> Unit)? = null//每个权限申请开始都会回调
        private var requestCode: Int = 1024
        fun permissions(permissions: Collection<String>): Builder {
            this.permissions.clear()
            this.permissions.addAll(permissions)
            return this
        }

        fun permissions(vararg permissions: String): Builder {
            this.permissions.clear()
            this.permissions.addAll(permissions)
            return this
        }

        fun onStart(onStart: (Requester) -> Unit): Builder {
            this.onStart = onStart
            return this
        }

        fun onStart2(onStart2: (Activity, String, Requester2) -> Unit): Builder {
            this.onStart2 = onStart2
            return this
        }

        fun onRationale(rationale: (String) -> Unit): Builder {
            this.onRationale = rationale
            return this
        }

        fun onGranted(onGranted: () -> Unit): Builder {
            this.onGranted = onGranted
            return this
        }

        fun onDenied(onDenied: (String) -> Unit): Builder {
            this.onDenied = onDenied
            return this
        }

        fun requestCode(requestCode: Int): Builder {
            this.requestCode = requestCode
            return this
        }

        fun request() {
            val request = PermissionRequester()
            request.permissions = permissions
            request.onRationale = onRationale
            request.onGranted = onGranted
            request.onDenied = onDenied
            request.onStart = onStart
            request.onStart2 = onStart2
            request.requestCode = requestCode
            QuickPermission.request = request
            request.startRequest(activity)
        }
    }
}
